using Autofac;
using Autofac.Extensions.DependencyInjection;
using BasicData.Domain.Entities;
using Consul;
using IGeekFan.AspNetCore.Knife4jUI;
using NLog.Web;
using Produce.Api.Filters;
using Produce.Api.MyAutoFac;
using Produce.Application;
using Produce.Application.Services;
using Produce.Domain.Entities;
using Produce.Infrastructure.Repositories;
using SqlSugar;
using System.Net;
using Yitter.IdGenerator;


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

//配置全局异常处理
builder.Services.AddControllers(x => x.Filters.Add<MyFilter>());

// 添加Swagger注释
builder.Services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "Produce.Api.xml", true));

//大小写一致
builder.Services.AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.PropertyNamingPolicy = null);

// SqlSugar 注册
builder.Services.AddScoped<ISqlSugarClient>(sp =>
    new SqlSugarClient(new ConnectionConfig
    {
        ConnectionString = builder.Configuration.GetConnectionString("MySQL"),
        DbType = DbType.MySql,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute,
        MoreSettings = new ConnMoreSettings
        {
            IsAutoRemoveDataCache = true,
            IsAutoDeleteQueryFilter = true
        }
    })
);



// 仓储与服务注册
builder.Services.AddScoped(typeof(IProduceModelRepository<>), typeof(ProduceModelRepository<>));


//builder.Services.AddScoped(typeof(IProduceModelAppService<>), typeof(ProduceModelAppService<>));

//实现autofac注入
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory(
                                                    x => x.RegisterModule(
                                                        new MyAutoFacs())));
builder.Services.AddAutofac();

//网关配置
builder.Services.AddSingleton<IConsulClient, ConsulClient>(p => new ConsulClient(cfg =>
{
    //consul地址
    cfg.Address = new Uri("http://120.26.197.100:8500");
}));

//配置automapper
builder.Services.AddAutoMapper(typeof(AutoMapping));

//配置日志
builder.Host.UseNLog();

//雪花id
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());

//--------------------------------------------------------------------------------------------------------


var app = builder.Build();

//跨域
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());


// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    //app.UseSwaggerUI();
    app.UseKnife4UI();
}

//静态文件
app.UseStaticFiles();


app.UseHttpsRedirection();

app.MapControllers();

app.MapGet("/health", () => Results.Ok("Ok"));

var consulClient = app.Services.GetRequiredService<IConsulClient>();
var registration = new AgentServiceRegistration
{
    ID = $"Produce-{Guid.NewGuid()}",
    Name = "Produce",
    Address = "120.26.197.100",  //公网
    Port = 8084, // 请根据实际端口调整
    Check = new AgentServiceCheck
    {
        HTTP = $"http://120.26.197.100:8084/health",
        Interval = TimeSpan.FromSeconds(10),
        Timeout = TimeSpan.FromSeconds(5),
        DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1) // 可选：健康检查失败多久后自动移除
    }
};
consulClient.Agent.ServiceRegister(registration).Wait();

//自动注入创建表Oracle数据库
using (var scope = app.Services.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
    db.CodeFirst.InitTables(typeof(ProductionWorkorder));
    db.CodeFirst.InitTables(typeof(ProductionDate));
    db.CodeFirst.InitTables(typeof(ProductionState));
    // 其他初始化...
}



app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
